/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.view.stripes;

import java.lang.reflect.Method;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.tag.LinkTag;

/**
 * Corresponds to {@link LinkTag} and {@code <s:link>}.
 *
 * @author Frederic Daoud
 */
public class SLink extends SLinkSupport<LinkTag, SLink> {
  private boolean labelSet;
  private String event;

  public SLink() {
    super(new LinkTag());
  }

  public void onInit() {
    beanclass(viewContext.getActionBean().getClass());
  }

  public SLink label(Object label) {
    add(label);
    labelSet = true;
    return getThis();
  }

  @Override
  public SLink beanclass(Class<? extends ActionBean> beanclass) {
    SLink result = super.beanclass(beanclass);
    try {
      Method method = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(beanclass);
      event = method.getName();
    }
    catch (Exception exc) {
      throw new RuntimeException(exc);
    }
    return result;
  }

  @Override
  public SLink event(String event) {
    SLink result = super.event(event);
    this.event = event;
    return result;
  }

  public SLink charset(String charset) {
    getTag().setCharset(charset);
    return getThis();
  }

  public SLink coords(String coords) {
    getTag().setCoords(coords);
    return getThis();
  }

  public SLink href(String href) {
    getTag().setHref(href);
    return getThis();
  }

  public SLink hreflang(String hreflang) {
    getTag().setHreflang(hreflang);
    return getThis();
  }

  public SLink rel(String rel) {
    getTag().setRel(rel);
    return getThis();
  }

  public SLink rev(String rev) {
    getTag().setRev(rev);
    return getThis();
  }

  public SLink shape(String shape) {
    getTag().setShape(shape);
    return getThis();
  }

  public SLink target(String target) {
    getTag().setTarget(target);
    return getThis();
  }

  public SLink type(String type) {
    getTag().setType(type);
    return getThis();
  }

  @Override
  public String toString() {
    labelFromBundle(event);
    return super.toString();
  }

  protected SLink labelFromBundle(String event) {
    if (!labelSet) {
      String label = bundle.get(event);
      if (label != null) {
        label(label);
      }
    }
    return getThis();
  }
}
